'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import {
  PlusIcon,
  MagnifyingGlassIcon,
  FunnelIcon,
  ArrowsUpDownIcon,
  ClockIcon,
  CheckCircleIcon,
  ArrowPathIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/24/outline';

// 项目类型定义
interface Project {
  id: string;
  name: string;
  description?: string;
  createdAt: string;
  updatedAt: string;
  owner?: {
    id: string;
    name?: string | null;
    avatar?: string | null;
    image?: string | null;
  } | null;
  status?: string;
  tags?: string[];
  memberCount?: number;
  taskCount?: number;
}

// 项目状态标签组件
const StatusBadge = ({ status }: { status: string }) => {
  switch (status) {
    case 'completed':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          <CheckCircleIcon className="mr-1 h-4 w-4" />
          已完成
        </span>
      );
    case 'in-progress':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          <ArrowPathIcon className="mr-1 h-4 w-4" />
          进行中
        </span>
      );
    case 'planning':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          规划中
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {status || '未知'}
        </span>
      );
  }
};

interface ProjectListProps {
  initialProjects: Project[];
}

export function ProjectList({ initialProjects }: ProjectListProps) {
  const router = useRouter();
  const [projects] = useState<Project[]>(initialProjects);
  const [searchTerm, setSearchTerm] = useState('');
  const [filter, setFilter] = useState({
    status: 'all',
  });
  const [sort, setSort] = useState({
    field: 'updatedAt',
    direction: 'desc',
  });

  // 过滤和搜索项目
  const filteredProjects = projects.filter(project => {
    // 状态过滤
    if (filter.status !== 'all' && project.status !== filter.status) return false;
    
    // 搜索过滤
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      return (
        project.name.toLowerCase().includes(searchLower) ||
        project.description?.toLowerCase().includes(searchLower) ||
        project.tags?.some(tag => tag.toLowerCase().includes(searchLower))
      );
    }
    
    return true;
  });

  // 排序项目
  const sortedProjects = [...filteredProjects].sort((a, b) => {
    const aValue = a[sort.field as keyof Project];
    const bValue = b[sort.field as keyof Project];
    
    if (typeof aValue === 'string' && typeof bValue === 'string') {
      return sort.direction === 'asc' 
        ? aValue.localeCompare(bValue) 
        : bValue.localeCompare(aValue);
    }
    
    return 0;
  });

  // 处理状态过滤变化
  const handleStatusFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setFilter(prev => ({ ...prev, status: e.target.value }));
  };

  // 处理排序变化
  const handleSortChange = (field: string) => {
    setSort(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'asc' ? 'desc' : 'asc',
    }));
  };

  return (
    <>
      {/* 搜索和过滤工具栏 */}
      <div className="mt-6 bg-white p-4 shadow rounded-lg">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
          <div className="max-w-lg w-full lg:max-w-xs">
            <label htmlFor="search" className="sr-only">搜索项目</label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
              </div>
              <input
                id="search"
                name="search"
                className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-[var(--primary-color)] focus:border-[var(--primary-color)] sm:text-sm"
                placeholder="搜索项目..."
                type="search"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
          <div className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
            <div className="flex items-center">
              <FunnelIcon className="h-5 w-5 text-gray-400 mr-2" />
              <label htmlFor="status-filter" className="text-sm font-medium text-gray-700 mr-2">
                状态:
              </label>
              <select
                id="status-filter"
                value={filter.status}
                onChange={handleStatusFilterChange}
                className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
              >
                <option value="all">全部</option>
                <option value="planning">规划中</option>
                <option value="in-progress">进行中</option>
                <option value="completed">已完成</option>
              </select>
            </div>
            <div className="flex items-center space-x-4">
              <span className="text-sm font-medium text-gray-700">排序:</span>
              <button
                type="button"
                onClick={() => handleSortChange('name')}
                className={`px-3 py-2 text-sm font-medium rounded-md ${
                  sort.field === 'name' 
                    ? 'bg-gray-100 text-gray-900' 
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                名称
                {sort.field === 'name' && (
                  <ArrowsUpDownIcon className="ml-1 h-4 w-4 inline" />
                )}
              </button>
              <button
                type="button"
                onClick={() => handleSortChange('updatedAt')}
                className={`px-3 py-2 text-sm font-medium rounded-md ${
                  sort.field === 'updatedAt' 
                    ? 'bg-gray-100 text-gray-900' 
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                最近更新
                {sort.field === 'updatedAt' && (
                  <ArrowsUpDownIcon className="ml-1 h-4 w-4 inline" />
                )}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 项目列表 */}
      <div className="mt-6">
        {sortedProjects.length > 0 ? (
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3">
            {sortedProjects.map((project) => (
              <div
                key={project.id}
                className="bg-white overflow-hidden shadow rounded-lg hover:shadow-md transition-shadow duration-200"
              >
                <div className="px-4 py-5 sm:p-6">
                  <div className="flex items-center justify-between">
                    <Link 
                      href={`/project/${project.id}`}
                      className="text-lg font-semibold text-gray-900 hover:text-[var(--primary-color)] truncate"
                    >
                      {project.name}
                    </Link>
                    <StatusBadge status={project.status || 'planning'} />
                  </div>
                  <p className="mt-1 text-sm text-gray-600 line-clamp-2">
                    {project.description || '无项目描述'}
                  </p>
                  <div className="mt-4">
                    <div className="flex items-center justify-between text-sm">
                      <div className="flex items-center text-gray-500">
                        <span className="mr-2">创建者:</span>
                        <div className="flex items-center">
                          {project.owner?.image || project.owner?.avatar ? (
                            <Image
                              src={project.owner.image || project.owner.avatar || '/user.svg'}
                              alt={project.owner.name || '用户'}
                              width={20}
                              height={20}
                              className="rounded-full mr-1"
                            />
                          ) : (
                            <div className="w-5 h-5 rounded-full bg-gray-200 mr-1 flex items-center justify-center text-xs">
                              {project.owner?.name?.charAt(0) || 'U'}
                            </div>
                          )}
                          <span>{project.owner?.name || '未知用户'}</span>
                        </div>
                      </div>
                      <span className="text-gray-500">
                        {project.memberCount || 1} 成员
                      </span>
                    </div>
                    <div className="mt-2 flex items-center justify-between text-sm">
                      <span className="text-gray-500">
                        {project.taskCount || 0} 任务
                      </span>
                      <span className="text-gray-500">
                        {new Date(project.updatedAt).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-12 bg-white shadow rounded-lg">
            <div className="text-gray-500">
              没有找到项目
            </div>
            <button
              className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
              onClick={() => router.push('/project/new')}
            >
              <PlusIcon className="h-5 w-5 mr-2" />
              创建新项目
            </button>
          </div>
        )}
      </div>
    </>
  );
} 